<?php

namespace App\Handlers;

class MaterialHandler
{

    /**
     * 库存扣减算法
     * @return string
     */
    public static function deduction_stock(array $stock, int $need)
    {
        $minimun = [];
        if (is_array($stock) && is_int($need)) {
            foreach ($stock as $key => $value) {
                $minimun[$key] = $value;
                if ($value['status'] == 1) {
                    if ((int)$value['stock'] >= (int)$need) {
                        $minimun[$key]['stock'] = (int)$value['stock'] - (int)$need;
                        $minimun[$key]['sell'] = (int)$value['sell'] + (int)$need;
                        if ((int)$value['stock'] == (int)$need) {
                            $minimun[$key]['status'] = 2;
                        }
                        break;
                    } else {
                        $minimun[$key]['stock'] = 0;
                        $minimun[$key]['sell'] = (int)$value['sell'] + (int)$value['stock'];
                        $minimun[$key]['status'] = 2;
                        $need = (int)$need - (int)$value['stock'];
                        continue;
                    }
                }
            }
        }
        return $minimun;
    }

    /**
     * 库存返回算法-取消订单
     */
    public static function return_stock(array $stock, int $need)
    {
        $minimun = [];
        if (is_array($stock) && is_int($need)) {
            foreach ($stock as $key => $value) {
                $minimun[$key] = $value;
                $minimun[$key]['stock'] = (int)$value['stock'] + (int)$need;
                $minimun[$key]['sell'] = (int)$value['sell'] - (int)$need;
                break;
            }
        }
        return $minimun;
    }


}